<template>
  <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}">
    <a-form-item label="key名称" v-bind="validateInfos.name">
      <a-input v-model:value="modelRef.name" v-focus />
    </a-form-item>
    <a-form-item label="有效时间" v-bind="validateInfos.rangeTime">
      <a-range-picker v-model:value="modelRef.rangeTime" valueFormat="YYYY年MM月DD日" format="YYYY年MM月DD日" :ranges="ranges" style="width:100%" />
    </a-form-item>
    <a-form-item label="服务列表" v-bind="validateInfos.interfaceCodes">
      <a-checkbox v-model:checked="checkAll" :indeterminate="indeterminate" @change="checkAllChange">全部</a-checkbox>
      <a-divider style="margin: 10px 0;" />
      <a-checkbox-group v-model:value="modelRef.interfaceCodes">
        <a-checkbox :value="item.code" v-for="item in interfaceData">{{item.name}}</a-checkbox>
      </a-checkbox-group>
    </a-form-item>
    <a-form-item label="限制上限" v-bind="validateInfos.sumCount">
      <a-input-number v-model:value="modelRef.sumCount" :min="0" addon-after="次" style="width:100%"/>
    </a-form-item>
    <a-form-item label="白名单">
      <a-textarea v-model:value="modelRef.whiteIp" style="min-height: 80px" placeholder="ip白名单,用分隔符,代表多个,例如:192.168.*.*,10.24.10.5(代表192.168下所有的段号和10.24.10.5可访问)"/>
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
      <a-space>
        <a-button @click="resetFields">重置</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>
<script>
import dayjs from "dayjs";
import { insert, update } from "@/api/platform/plAppKeyApi";
import { all } from "@/api/platform/plInterfaceApi";
import {
  defineComponent,
  reactive,
  toRaw,
  toRefs,
  onMounted,
  watch
} from "vue";
import { Form, message } from "ant-design-vue";
const useForm = Form.useForm;
export default defineComponent({
  props: {
    type: String,
    row: Object,
    appCode: String
  },
  setup(props, context) {
    const { type, appCode, row } = props;
    const data = reactive({
      interfaceData: [],
      checkAll: false,
      indeterminate: false,
      checkedAllList: []
    });

    const ranges = reactive({
      "今天": [dayjs(), dayjs()],
      "本周": [dayjs(), dayjs().endOf("week")],
      "本月": [dayjs(), dayjs().endOf("month")],
      "30天": [dayjs(), dayjs().add(30, 'day')],
      "今年": [dayjs(), dayjs().endOf("year")],
    });
    const modelRef = reactive({
      name: row?.name,
      code: row?.code,
      appCode: appCode,
      rangeTime:
        row?.startTime && row?.endTime ? [row?.startTime, row?.endTime] : null,
      sumCount: row?.sumCount || 1000,
      whiteIp: row?.whiteIp,
      interfaceCodes: row?.interfaceCodeStr
        ? row?.interfaceCodeStr.split(",")
        : []
    });
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "key名称必填项"
        }
      ],
      rangeTime: [
        {
          required: true,
          message: "有效时间必填项"
        }
      ],
      interfaceCodes: [
        {
          required: true,
          message: "服务接口必选项",
          type: "array"
        }
      ],
      sumCount: [
        {
          required: true,
          message: "调用上限必填项"
        }
      ]
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const onSubmit = () => {
      validate()
        .then(() => {
          if (type == "insert") {
            insertData();
          } else if (type == "update") {
            updateData();
          }
        })
        .catch(err => {
          console.log("error", err);
        });
    };

    const insertData = () => {
      let form = toRaw(modelRef);
      form.startTime = form.rangeTime[0];
      form.endTime = form.rangeTime[1];
      insert(form).then(resd => {
        message.success("创建成功");
        context.emit("success", resd);
      });
    };

    const updateData = () => {
      let form = toRaw(modelRef);
      form.id = row.id;
      form.startTime = form.rangeTime[0];
      form.endTime = form.rangeTime[1];
      update(form).then(resd => {
        message.success("更新成功");
        context.emit("success", resd);
      });
    };

    /**查询所有的接口信息 */
    const initInterfaceAll = () => {
      all().then(resd => {
        data.interfaceData = resd;
        resd.forEach(item => {
          data.checkedAllList.push(item.code);
        });
         // 监听全选的状态
      data.indeterminate = !!modelRef.interfaceCodes.length && modelRef.interfaceCodes .length < data.checkedAllList.length;
      data.checkAll = modelRef.interfaceCodes.length === data.checkedAllList.length;
      });
    };

    /**初始化页面操作 */
    onMounted(() => {
      initInterfaceAll();
    });

    /**全选 非全选状态 */
    const checkAllChange = e => {
      (modelRef.interfaceCodes = e.target.checked ? data.checkedAllList : []),
        (data.indeterminate = false);
    };

    watch(
      () => modelRef.interfaceCodes,
      val => {
        data.indeterminate =
          !!val.length && val.length < data.checkedAllList.length;
        data.checkAll = val.length === data.checkedAllList.length;
      }
    );

    return {
      ...toRefs(data),
      validateInfos,
      resetFields,
      modelRef,
      ranges,
      onSubmit,
      checkAllChange
    };
  }
});
</script>